package com.framework.core.utils;


import org.apache.tomcat.util.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author 樊猛 [986314249@qq.com]
 * @create 2018/5/23 16:30
 */
public class SerializableUtils {

    public static String serialize(Object object) {
        if (object == null){
            return null;
        }
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
           // return Base64.encode(bos.toByteArray());
            return Base64.encodeBase64String(bos.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException("serialize object error", e);
        }
    }
    public static Object deserialize(String objectStr) {
        if (objectStr == null || "".equals(objectStr)){
            return null;
        }
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(objectStr));
            ObjectInputStream ois = new ObjectInputStream(bis);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException("deserialize object error", e);
        }
    }
}
